<template>
  <el-button type="primary" @click="handleClick" color="#5cb85c">
    <span v-if="!showHeatMap">生成</span>
    <span v-else>取消</span>
    事件热力图
  </el-button>
</template>

<script setup>
import { Query } from '../../../utils/Query';

const $map = ref(null);
const heatMapSource = ref(null);
let showHeatMap = ref(false);
const emit = defineEmits(['changeShow']);

onMounted(() => {
  $map.value = inject('$map');

  //热力图
  heatMapSource.value = new ol.source.Vector({});
  let heatMapLayer = new ol.layer.Heatmap({
    source: heatMapSource.value,
    gradient: ['#00f', '#0ff', '#0f0', '#ff0', '#f00'], //颜色
    blur: 25, // 模糊半径
    radius: 20, //半径
  });
  $map.value.addLayer(heatMapLayer);
});

//关闭dialog对话框时，清空热力图层
onBeforeUnmount(() => {
  heatMapSource.value.clear();
});

// 点击按钮时控制热力图层显隐
function handleClick() {
  showHeatMap.value = !showHeatMap.value;
  //向EventQuery组件传递heatMap显隐状态
  emit('changeShow', showHeatMap.value);
  if (showHeatMap.value) {
    const service = {
      name: 'guanggu',
      layerId: 2,
    };
    // 调用图层查询方法
    Query.queryByLayerId({
      service,
      callback: handleQuery,
    });
  } else {
    heatMapSource.value.clear();
  }
}
// 图层查询回调
function handleQuery(data) {
  //将要素转为ol要素类型，添加到热力图层
  var format = new Zondy.Format.PolygonJSON();
  let features = format.read(data);
  heatMapSource.value.addFeatures(features);
}
</script>

<style lang="scss" scoped>
.el-button {
  background-color: #5cb85c;
  border: none;
}
</style>
